var express = require("express");
const fs = require("fs");
const { dirname } = require("path");
var router = express.Router();

const SYSTEM_KEY = "JHIJfdswqefsdDfro21gmdsl2";

router.post("/updatestatus", function (req, res, next) {
  console.log(req.body);
  const { user, key, status } = req.body;
  if (status !== "offline" && status !== "online") {
    res.send({
      code: 500,
      msg: "请传递正确的status字段(offline|online)",
    });
    return;
  }
  if (user === "glack" && key === SYSTEM_KEY) {
    let str = fs.readFileSync(__dirname + "/../utils/system.json");
    let obj = JSON.parse(str);
    obj.status = status;

    fs.writeFileSync(__dirname + "/../utils/system.json", JSON.stringify(obj));

    res.send({
      code: 1,
      msg: "修改成功",
      status: "当前状态:" + status,
    });
  } else {
    res.send({
      code: 500,
      msg: "修改失败,参数错误",
    });
  }
});

/**
 * 三个字段 user: glack, key, status
 */
router.post("/getstatus", function (req, res, next) {
  console.log(req.body);
  const { user, key } = req.body;
  if (user === "glack" && key === SYSTEM_KEY) {
    let str = fs.readFileSync(__dirname + "/../utils/system.json");

    res.send({
      code: 1,
      msg: "操作成功",
      status: JSON.parse(str).status,
    });
  } else {
    res.send({
      code: 500,
      msg: "查看失败,参数错误",
    });
  }
});

module.exports = router;
